'use client'

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Loader2, FileSpreadsheet, ArrowLeft, Save, CheckCircle, XCircle, AlertCircle, Filter } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { Input } from "@/components/ui/input"
import DataSourceFilter from './data-source-filter'
import { validateParameterValue, generatePlaceholder } from '@/lib/data-validation'
import { canEditByRole } from '@/lib/data-entry-permissions'
import { Table } from 'antd'
import type { ValidationResult } from '../lib/data-validation'
import type { ColumnsType } from 'antd/es/table'

const PARAMETER_HEADERS = [
  { key: 'sequence', label: '序号', width: 'w-12' },
  { key: 'parameter_name', label: '中文名称', width: 'w-48' },
  { key: 'example_description', label: '示例或属性说明', width: 'w-56' },
  { key: 'data_type', label: '数据类型', width: 'w-24' },
  { key: 'measurement_class', label: '计量类', width: 'w-24' },
  { key: 'measurement_unit', label: '计量单位', width: 'w-24' },
  { key: 'data_source', label: '数据来源', width: 'w-24' },
  { key: 'parameter_value', label: '数据录入', width: 'w-40' },
  { key: 'validation', label: '数据校验', width: 'w-32' }
];

interface Parameter {
  id: number;
  sequence: number;
  parameter_name: string;
  example_description: string;
  data_type: string;
  measurement_class: string;
  measurement_unit: string;
  data_source: string;
  parameter_value: string;
  validation_status?: string;
  validation_message?: string;
  [key: string]: any;
}

interface ParameterTableProps {
  deviceId: string;
  parameters: Parameter[];
  measurementUnitMap: Record<string, string>;
  currentUserRole: string;
  isPositionTable?: boolean;
  isEditing?: boolean;
  onSave: (parameters: Parameter[]) => Promise<void>;
  onEditingChange?: (editing: boolean) => void;
}

// 智能占位符函数
function getSimplePlaceholder(dataType: string, parameterName: string) {
  if (parameterName && parameterName.includes('坐标')) {
    return '坐标系名称（X 坐标，Y 坐标，Z 坐标）';
  }
  if (dataType && dataType.includes('日期')) {
    return 'YYYY-MM-DD';
  }
  if (dataType && (dataType.includes('数值') || dataType.includes('数字'))) {
    return '请输入数值';
  }
  return '请输入文本';
}

export default function ParameterTable({
  deviceId,
  parameters,
  measurementUnitMap,
  currentUserRole,
  isPositionTable = false,
  isEditing = false,
  onSave,
  onEditingChange
}: ParameterTableProps) {
  const [editData, setEditData] = useState<Record<string, string>>({});
  const { toast } = useToast();
  const [validationResults, setValidationResults] = useState<Record<string, ValidationResult>>({});
  const [dataSourceFilter, setDataSourceFilter] = useState<string>('all');

  // 根据数据来源筛选参数
  const filteredParameters = parameters.filter(param => {
    if (dataSourceFilter === 'all') return true;
    return param.data_source === dataSourceFilter;
  });

  const handleSave = async () => {
    try {
      const updatedParameters = parameters.map(param => ({
        ...param,
        parameter_value: editData[param.key] ?? param.parameter_value
      }));

      await onSave(updatedParameters);

      onEditingChange?.(false);
      toast({
        title: "保存成功",
        description: "参数数据已更新",
      });
    } catch (error) {
      toast({
        title: "保存失败",
        description: error instanceof Error ? error.message : "未知错误",
        variant: "destructive",
      });
    }
  };

  // 字段映射，兼容后端返回的驼峰式和空格字段
  const mappedParameters = filteredParameters.map((item, idx) => ({
    ...item,
    sequence: typeof item.sequence === 'number' ? item.sequence : Number(item.sequence) || idx + 1,
    parameter_name: item.parameter_name || item.Chinese_name || '',
    example_description: item.example_description || item.example_or_attribute_description || item['example or attribute description'] || '',
    measurement_class: item.measurement_class || item.metrology_class || '',
  }));

  const columns: ColumnsType<Parameter> = [
    {
      title: '序号',
      dataIndex: 'sequence',
      width: '8%',
      render: (text: number) => <span>{text}</span>
    },
    {
      title: '中文名称',
      dataIndex: 'parameter_name',
      width: '15%',
      render: (text: string) => <span>{text || '-'}</span>
    },
    {
      title: '示例或属性说明',
      dataIndex: 'example_description',
      width: '22%',
      render: (text: string) => <span>{text || '-'}</span>
    },
    {
      title: '数据类型',
      dataIndex: 'data_type',
      width: '10%',
      render: (text: string) => <span>{text}</span>
    },
    {
      title: '计量类',
      dataIndex: 'measurement_class',
      width: '6%',
      render: (text: string) => <span>{text || '-'}</span>
    },
    {
      title: '计量单位',
      dataIndex: 'measurement_unit',
      width: '6%',
      render: (_: string, record: Parameter) => {
        const unit = measurementUnitMap?.[record.measurement_class] || record.measurement_unit || '-';
        return <span>{unit}</span>;
      }
    },
    {
      title: '数据来源',
      dataIndex: 'data_source',
      width: '6%',
      render: (text: string) => <span>{text || '-'}</span>
    },
    {
      title: '数据录入',
      dataIndex: 'parameter_value',
      width: '15%',
      render: (text: string, record: Parameter) => {
        const placeholder = getSimplePlaceholder(record.data_type, record.parameter_name || '');
        const recordKey = record.id?.toString() ?? record.sequence?.toString() ?? record.key?.toString() ?? '';
        const validationResult = validationResults[recordKey];
        
        const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
          const newValue = e.target.value;
          setEditData({ ...editData, [recordKey]: newValue });
          
          // 实时校验
          if (newValue.trim() !== '') {
            const unit = measurementUnitMap?.[record.measurement_class] || record.measurement_unit;
            const result = validateParameterValue(
              newValue,
              record.data_type,
              unit,
              record.example_description,
              isPositionTable
            );
            setValidationResults(prev => ({ ...prev, [recordKey]: result }));
          } else {
            // 空值时清除校验结果
            setValidationResults(prev => ({ ...prev, [recordKey]: { isValid: true } }));
          }
        };
        
                  return (
            <div style={{ margin: 0 }}>
              <Input
                placeholder={placeholder}
                value={editData[recordKey] ?? text ?? ''}
                onChange={handleInputChange}
                size="small"
                disabled={!isEditing}
              />
            </div>
          );
      }
    },
    {
      title: '数据校验',
      dataIndex: 'validation_status',
      width: '10%',
      render: (_: any, record: Parameter) => {
        const recordKey = record.id?.toString() ?? record.sequence?.toString() ?? record.key?.toString() ?? '';
        const value = isEditing ? editData[recordKey] : record.parameter_value;
        const validationResult = validationResults[recordKey];
        if (!value || value.trim() === '') {
          return <span style={{ color: '#999' }}>无数据</span>;
        }
        if (validationResult?.isValid === false) {
          return <span style={{ color: '#ff4d4f' }}>{validationResult.message || '不通过'}</span>;
        }
        return <span style={{ color: '#52c41a' }}>通过</span>;
      }
    }
  ];

  useEffect(() => {
    const initialValidations: Record<string, ValidationResult> = {};
    const initialEditData: Record<string, string> = {};
    
    parameters.forEach((record, idx) => {
      const recordKey = record.id?.toString() ?? record.sequence?.toString() ?? idx.toString();
      
      // 初始化编辑数据
      initialEditData[recordKey] = record.parameter_value || '';
      
      // 初始化验证结果
      if (record.parameter_value) {
        const unit = measurementUnitMap?.[record.measurement_class] || record.measurement_unit;
        initialValidations[recordKey] = validateParameterValue(
          record.parameter_value,
          record.data_type,
          unit,
          record.example_description,
          isPositionTable
        );
      } else {
        initialValidations[recordKey] = { isValid: true };
      }
    });
    
    setEditData(initialEditData);
    setValidationResults(initialValidations);
  }, [parameters, measurementUnitMap, isPositionTable]);

  return (
    <div className="bg-white overflow-hidden">
      {/* 数据来源筛选控件 */}
      <DataSourceFilter
        currentFilter={dataSourceFilter}
        onFilterChange={setDataSourceFilter}
        parameters={parameters}
        className="mb-6"
      />

      <div className="overflow-x-auto">
        <Table
          dataSource={mappedParameters.map((item, idx) => ({
            ...item,
            key: item.id ?? item.sequence ?? idx
          }))}
          columns={columns}
          pagination={false}
          rootClassName="blue-header-table"
          size="small"
        />
      </div>
    </div>
  );
} 